package com.zlsy.thread.objectandthreadcommonsuse.parity;

/**
 * @author zhouliang
 * @date 2020/03/06
 * @Desc 两个线程交替打印0~100的奇偶数，要求：偶线程打印0，奇线程打印1，如此循环往复 ：wait实现
 **/
public class ParityPrintingByWaitAndNotify {

    private static int count;

    private static final Object lock = new Object();

    static class TurningRuner implements Runnable {

        @Override
        public void run() {
            while (count <= 100) {
                synchronized (lock) {
                    System.out.println(Thread.currentThread().getName() + ",打印：" + count++);
                    //打印完，唤醒另外一个线程，交替打印
                    lock.notify();
                    if (count <= 100) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        TurningRuner instance = new TurningRuner();
        Thread thread = new Thread(instance);
        Thread thread1 = new Thread(instance);
        thread.setName("偶数");
        thread1.setName("奇数");
        thread.start();
        Thread.sleep(100);
        thread1.start();
    }
}
